package com.anjubao.parking.municipal.common.global;

import java.io.IOException;

import com.anjubao.parking.municipal.common.utils.U;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.BeanProperty;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.deser.ContextualDeserializer;
import com.fasterxml.jackson.databind.deser.std.EnumDeserializer;

import lombok.Data;
import lombok.EqualsAndHashCode;

/**
 * 枚举值反序列化（必须继承BaseEnum）
 * @author Atom.zyu
 *
 */
@Data
@EqualsAndHashCode(callSuper = false)
public class EnumJsonDeserializer extends JsonDeserializer<Enum> implements ContextualDeserializer {
	private Class<Enum> clz;

	@Override
	public EnumJsonDeserializer createContextual(DeserializationContext ctx, BeanProperty property) throws JsonMappingException {
		Class<Enum> rawCls = (Class<Enum>) ctx.getContextualType().getRawClass();
		EnumJsonDeserializer clone = new EnumJsonDeserializer();
		clone.setClz(rawCls);
		return clone;
	}

	@Override
	public Enum deserialize(JsonParser p, DeserializationContext ctx) throws IOException, JsonProcessingException {
		String valueStr = p.getText();
		if (U.isEmpty(valueStr)) {
			return null;
		}
		// 原始枚举转换
		if (!BaseEnum.class.isAssignableFrom(clz)) {
			return Enum.valueOf(clz, valueStr);
		}
		// BaseEnum转换
		Enum[] bes = clz.getEnumConstants();
		for (Enum be : bes) {
			if (((BaseEnum) be).getCode() == Integer.parseInt(valueStr)) {
				return (Enum) be;
			}
		}
		return null;
	}

}
